package com.ruoyi.wvp.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.wvp.domain.AddressUnit;
import com.ruoyi.wvp.domain.Surveillance;
import com.ruoyi.wvp.entity.HomePageParams;
import com.ruoyi.wvp.service.IAddressUnitService;
import com.ruoyi.wvp.service.ISurveillanceService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.wvp.domain.CommunityEventCount;
import com.ruoyi.wvp.service.ICommunityEventCountService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.enums.DeletedEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.client.RestTemplate;

/**
 * 社区事件统计Controller
 * 
 * @author ruoyi
 * @date 2024-08-25
 */
@RestController
@RequestMapping("/wvp/communityEventCount")
@Tag(name = "【社区事件统计】管理")
public class CommunityEventCountController extends BaseController{
    @Autowired
    private ICommunityEventCountService communityEventCountService;
    @Autowired
    private IAddressUnitService addressUnitService;
    @Autowired
    private ISurveillanceService surveillanceService;

    /**
     * 查询社区事件统计列表
     */
    @Operation(summary = "查询社区事件统计列表")
    @PreAuthorize("@ss.hasPermi('wvp:communityEventCount:list')")
    @GetMapping("/list")
    public TableDataInfo list(CommunityEventCount communityEventCount) {
        Page<CommunityEventCount> page = getPage();
        communityEventCountService.pageList(page, communityEventCount);
        return getTableDataInfo(page);
    }


    /**
     * 导出社区事件统计列表
     */
    @Operation(summary = "导出社区事件统计列表")
    @PreAuthorize("@ss.hasPermi('wvp:communityEventCount:export')")
    @Log(title = "社区事件统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportAll(HttpServletResponse response,CommunityEventCount communityEventCount){
        List<CommunityEventCount> list = communityEventCountService.listAll(communityEventCount);
        ExcelUtil<CommunityEventCount> util = new ExcelUtil<CommunityEventCount>(CommunityEventCount.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取社区事件统计详细信息
     */
    @Operation(summary = "获取社区事件统计详细信息")
    @PreAuthorize("@ss.hasPermi('wvp:communityEventCount:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id){
        return success(communityEventCountService.getById(id));
    }

    /**
     * 新增社区事件统计
     */
    @Operation(summary = "新增社区事件统计")
    @PreAuthorize("@ss.hasPermi('wvp:communityEventCount:add')")
    @Log(title = "社区事件统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommunityEventCount communityEventCount){
        return toAjax(communityEventCountService.save(communityEventCount));
    }

    /**
     * 修改社区事件统计
     */
    @Operation(summary = "修改社区事件统计")
    @PreAuthorize("@ss.hasPermi('wvp:communityEventCount:edit')")
    @Log(title = "社区事件统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommunityEventCount communityEventCount){
        return toAjax(communityEventCountService.updateById(communityEventCount));
    }

    /**
     * 删除社区事件统计
     */
    @Operation(summary = "删除社区事件统计")
    @PreAuthorize("@ss.hasPermi('wvp:communityEventCount:remove')")
    @Log(title = "社区事件统计", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable( name = "ids" ) Long[] ids) {
        QueryWrapper<CommunityEventCount> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",List.of(ids));
        CommunityEventCount communityEventCount = new CommunityEventCount();
        return toAjax(communityEventCountService.update(communityEventCount,queryWrapper));
    }


    @Operation(summary = "同步社区事件统计")
    @PostMapping("/listByDate")
    public AjaxResult listByDate(@RequestBody HomePageParams homePageParams){
        CommunityEventCount communityEventCount=new CommunityEventCount();
        communityEventCount.setMonth(homePageParams.getMonth());
        List<CommunityEventCount> data = communityEventCountService.listAll(communityEventCount,homePageParams);

        Surveillance surveillance=new Surveillance();
        List<Surveillance> surveillances = surveillanceService.listAll(surveillance);
        HashSet<Long> communityCodes = new HashSet<>(surveillances.size());
        surveillances.forEach(s -> {
            communityCodes.add(Long.valueOf(s.getCommunityCode()));
        });

//        List<String> codes = data.stream().map(CommunityEventCount::getCommunityCode).collect(Collectors.toList());
        LambdaQueryWrapper<AddressUnit> addressUnitQueryWrapper = new LambdaQueryWrapper<AddressUnit>();
        addressUnitQueryWrapper.in(AddressUnit::getId,communityCodes);
        List<AddressUnit> list = addressUnitService.list(addressUnitQueryWrapper);
        Collections.sort(list);
        Map<String, CommunityEventCount> sMap = data.stream().collect(Collectors.toMap(CommunityEventCount::getCommunityCode, item -> item));
        List<CommunityEventCount> retData = new ArrayList<>(list.size());
        list.forEach(item->{
            CommunityEventCount communityEventCountTmp = sMap.get(item.getId().toString());
            if(communityEventCountTmp!=null){
                communityEventCountTmp.setCommunity(item.getName());

            }else{
                communityEventCountTmp=new CommunityEventCount();
                communityEventCountTmp.setEventCount(0L);
                communityEventCountTmp.setCommunity(item.getId().toString());
                communityEventCountTmp.setCommunity(item.getName());
            }
            retData.add(communityEventCountTmp);
        });

//        Map<Long, String> addressMap = list.stream().collect(Collectors.toMap(AddressUnit::getId, AddressUnit::getName));
//        ArrayList<CommunityEventCount> retData = new ArrayList<>(data.size());
//        data.forEach(item->{
//            Long key = Long.valueOf(item.getCommunityCode());
//            if(addressMap.containsKey(key)){
//                item.setCommunity(addressMap.get(key));
//                retData.add(item);
//            }
//        });
        return success(retData);
    }

    @Operation(summary = "设备统计")
    @PostMapping("/statistics")
    public AjaxResult statistics(@RequestBody HomePageParams homePageParams){
        return success(communityEventCountService.statistics(homePageParams));
    }


    @Autowired
    private ResourceLoader resourceLoader;

    @GetMapping("/test")
    @Anonymous
    public AjaxResult test() throws IOException {
        String s = new RestTemplate().getForObject("https://tt.dailyrecycle.cn/nsindex.json", String.class);
//        Resource resource = resourceLoader.getResource("classpath:nsindex.json");
//        String s = new String(Files.readAllBytes(Paths.get(resource.getURI())));
        JSONObject jsonObject = JSON.parseObject(s);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray content = data.getJSONArray("content");
        Surveillance surveillance;
        for (Object item : content) {
            JSONObject jo = (JSONObject) item;
            surveillance = new Surveillance();
            String latitude = jo.getString("latitude");//纬度
            String longitude = jo.getString("longitude");//经度
            surveillance.setLatitude(latitude);
            surveillance.setLongitude(longitude);
            surveillanceService.updateBySerialNumber(jo.getString("serialNo"),surveillance);
            System.out.println(item);
        }
        return success();
    }



}
